package org.harsh.common.crypt;

import org.harsh.common.Config;
import org.harsh.common.Util;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.SecretKey;


/**
 * Created by liuhaibo on 2024/7/15.
 */
public abstract class AbsCrypt implements ICrypt {
    static Cipher enCipher;
    static Cipher deCipher;

    static String cryptMode;
    static SecretKey secretKey;

    public void init() {
        try {
            enCipher = Cipher.getInstance(cryptMode);
            enCipher.init(Cipher.ENCRYPT_MODE, secretKey);
            deCipher = Cipher.getInstance(cryptMode);
            deCipher.init(Cipher.DECRYPT_MODE, secretKey);
        } catch (Exception e){
            e.printStackTrace();
        }
    }
    @Override
    public byte[] encrypt(byte[] data) {
        try {
            return enCipher.doFinal(data);
        } catch (IllegalBlockSizeException e) {
            throw new RuntimeException(e);
        } catch (BadPaddingException e) {
            throw new RuntimeException(e);
        }
    }

    // 加密用默认编码，实现从字符串到字节数组
    @Override
    public byte[] encryptStr(String data) {
        return encrypt(data.getBytes(Config.DEFAULT_CHARSET));
    }

    // 加密后用base64将字符串编码为可读形式
    @Override
    public String encryptToStr(byte[] data) {
        return Util.base64Encode(encrypt(data));
    }

    // 加密后用base64将字符串编码为可读形式
    @Override
    public String encryptStrToStr(String data) {
        return Util.base64Encode(encryptStr(data));
    }

    // 解码
    @Override
    public byte[] decrypt(byte[] data) {
        try {
            return deCipher.doFinal(data);
        } catch (IllegalBlockSizeException e) {
            throw new RuntimeException(e);
        } catch (BadPaddingException e) {
            throw new RuntimeException(e);
        }
    }

    // 对字符串的解码用base64进行先解码
    @Override
    public byte[] decryptStr(String data) {
        return decrypt(Util.base64Decode(data));
    }

    @Override
    public String decryptToStr(byte[] data) {
        return new String(data, Config.DEFAULT_CHARSET);
    }

    @Override
    public String decryptStrToStr(String data) {
        return new String(decryptStr(data), Config.DEFAULT_CHARSET);
    }
}
